package com.lcf.app.es.service;

import com.lcf.app.es.model.Article;
import com.lcf.app.es.repository.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author ChenFei
 * @date 2021/12/8
 */
@Service
public class ArticleService {

    @Resource
    private ArticleRepository articleRepository;

    /**
     * 也可以使用这个 ： ElasticsearchOperations
     */
    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    public Article save(Article article) {
        return articleRepository.save(article);
    }

    public Iterable<Article> findAll() {
        return articleRepository.findAll();
    }

    public Page<Article> page(Integer pageNum, Integer pageSize) {
        Integer offset = (pageNum - 1) * pageSize;
        PageRequest pageRequest = PageRequest.of(offset, pageSize);
        return articleRepository.findAll(pageRequest);
    }

    /**
     * 条件查询案例：
     *
     * @param keywords
     * @return
     */
    public SearchHits<Article> findByKeywords(String keywords) {
        Criteria criteria = new Criteria("content").contains(keywords)
                .or("title").contains(keywords)
                .or("SearchHits<Article>").contains(keywords);
        CriteriaQuery query = new CriteriaQuery(criteria);
        //query.setPageable()
        return elasticsearchRestTemplate.search(query, Article.class);
    }

    /**
     * eg: 嵌套查询
     * Criteria miller = new Criteria("lastName").is("Miller")
     *   .subCriteria(
     *     new Criteria().or("firstName").is("John")
     *       .or("firstName").is("Jack")
     *   );
     * Query query = new CriteriaQuery(criteria);
     */

    /**
     * 字符串查询
     * Query query = new SearchQuery("{ \"match\": { \"firstname\": { \"query\": \"Jack\" } } } ");
     * SearchHits<Person> searchHits = operations.search(query, Person.class);
     */

    /**
     * 直接定义方法进行查询
     *
     * @param content
     * @return
     */
    public List<Article> findByContentContaining(String content) {
        return articleRepository.findByContentContaining(content);
    }

    public Page<Article> listByTitle(String title) {
        PageRequest pageRequest = PageRequest.of(0, 10);
        return articleRepository.listByTitle(title, pageRequest);
    }

}
